package com.keba.lamp.complaint.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.basic.database.mybatis.conditions.Wraps;
import com.keba.basic.database.mybatis.conditions.query.LbQueryWrap;
import com.keba.lamp.common.constant.AppendixType;
import com.keba.lamp.common.constant.BizConstant;
import com.keba.lamp.complaint.entity.ComFileRel;
import com.keba.lamp.complaint.entity.Plaintff;
import com.keba.lamp.complaint.manager.ComFileRelManager;
import com.keba.lamp.complaint.manager.PlaintffManager;
import com.keba.lamp.complaint.service.PlaintffService;
import com.keba.lamp.complaint.vo.result.CaseFileResultVO;
import com.keba.lamp.complaint.vo.result.PlaintffResultVO;
import com.keba.lamp.complaint.vo.save.PlaintffSaveVO;
import com.keba.lamp.complaint.vo.update.PlaintffSummarizeUpdateVO;
import com.keba.lamp.complaint.vo.update.PlaintffUpdateVO;
import com.keba.lamp.file.entity.File;
import com.keba.lamp.file.service.AppendixService;
import com.keba.lamp.file.service.FileService;
import com.keba.lamp.model.vo.result.AppendixResultVO;
import com.keba.lamp.model.vo.save.AppendixSaveVO;
import com.keba.lamp.system.manager.system.DefParameterManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 原告信息
 * </p>
 *
 * @author chaowu.wang
 * @date 2025-03-14 23:03:53
 * @create [2025-03-14 23:03:53] [chaowu.wang] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PlaintffServiceImpl extends SuperServiceImpl<PlaintffManager, Long, Plaintff> implements PlaintffService {

    private final AppendixService appendixService;
    private final FileService fileService;
    private final ComFileRelManager comFileRelManager;
    private final DefParameterManager defParameterManager;

    @Override
    public void save(List<PlaintffSaveVO> plaintffSaveVOList, Long caseId) {
        if (CollectionUtil.isEmpty(plaintffSaveVOList)) {
            //未上传原告
            return;
        }
        plaintffSaveVOList.stream().forEach(plaintffSaveVO -> {
            plaintffSaveVO.setCaseId(caseId);
            Plaintff plaintff = this.save(plaintffSaveVO);
            List<Long> fileIdList = plaintffSaveVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(plaintff.getId(), AppendixType.Complaint.COMPLAINT__PLAINTFF__FILE,
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public void update(List<PlaintffUpdateVO> plaintffUpdateVOList, Long caseId) {
        if (CollectionUtil.isEmpty(plaintffUpdateVOList)) {
            //未上传原告信息
            this.deleteByCaseIds(Lists.newArrayList(caseId));
            return;
        }
        List<Long> updateIdList = plaintffUpdateVOList.stream().filter(vo ->
                Objects.nonNull(vo.getId())
        ).map(PlaintffUpdateVO::getId).collect(Collectors.toList());
        List<Plaintff> oldplaintffList = this.findByCaseId(caseId);

        //1、需要删除的原告信息
        List<Long> delPlainffIdList = oldplaintffList.stream().filter(oldPlaintff ->
                !updateIdList.contains(oldPlaintff.getId())
        ).map(Plaintff::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delPlainffIdList)) {
            appendixService.removeByBizId(delPlainffIdList, AppendixType.Complaint.COMPLAINT__PLAINTFF__FILE);
            this.removeByIds(delPlainffIdList);
        }

        //2、需要新增或更新的原告信息
        plaintffUpdateVOList.stream().filter(plaintffUpdateVO ->
            Objects.isNull(plaintffUpdateVO.getId()) || !delPlainffIdList.contains(plaintffUpdateVO.getId())
        ).forEach(plaintffVO -> {
            Plaintff plaintff = BeanUtil.toBean(plaintffVO, Plaintff.class);
            plaintff.setCaseId(caseId);
            superManager.saveOrUpdate(plaintff);

            List<Long> fileIdList = plaintffVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(plaintff.getId(), AppendixType.Complaint.COMPLAINT__PLAINTFF__FILE,
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public List<Plaintff> findByCaseId(Long caseId) {
        LbQueryWrap<Plaintff> queryWrap = Wraps.<Plaintff>lbQ().eq(Plaintff::getCaseId, caseId);
        return list(queryWrap);
    }

    @Override
    public List<PlaintffResultVO> getResultByCaseId(Long caseId) {
        List<Plaintff> plaintffList = this.findByCaseId(caseId);
        List<PlaintffResultVO> resultVOList = plaintffList.stream().map(plaintff -> {
            PlaintffResultVO plaintffResultVO = BeanUtil.toBean(plaintff, PlaintffResultVO.class);
            List<AppendixResultVO> appendixResultVOS = appendixService.listByBizIdAndBizType(plaintff.getId(), AppendixType.Complaint.COMPLAINT__PLAINTFF__FILE);
            if (CollectionUtil.isEmpty(appendixResultVOS)) {
                //未上传原告图片
                return plaintffResultVO;
            }

            List<Long> fileIdList = appendixResultVOS.stream().map(AppendixResultVO::getId).collect(Collectors.toList());
            List<File> files = fileService.listByIds(fileIdList);
            //Map<Long, String> accessUrlMap = fileService.findUrlById(fileIdList);
            Map<Long, File> fileMap = files.stream().collect(Collectors.toMap(File::getId, Function.identity()));
            List<CaseFileResultVO> plaintffFileResultVOList = appendixResultVOS.stream().map(appendixResultVO -> {
                File file = fileMap.get(appendixResultVO.getId());
                CaseFileResultVO caseFileResultVO = new CaseFileResultVO();
                BeanUtils.copyProperties(file, caseFileResultVO);
                BeanUtils.copyProperties(appendixResultVO, caseFileResultVO);
                //caseFileResultVO.setUrl(accessUrlMap.get(file.getId()));
                setPicList(file, caseFileResultVO);
                return caseFileResultVO;
            }).sorted(Comparator.comparing(CaseFileResultVO::getSortValue)).collect(Collectors.toList());
            plaintffResultVO.setFileList(plaintffFileResultVOList);
            return plaintffResultVO;
        }).collect(Collectors.toList());
        return resultVOList;
    }


    private void setPicList(File file, CaseFileResultVO caseFileResultVO) {
        if (BizConstant.SUFFIX_PDF.equalsIgnoreCase(file.getSuffix())) {
            ComFileRel comFileRel = comFileRelManager.getByFileId(file.getId());
            caseFileResultVO.setPicNum(Objects.nonNull(comFileRel) ? comFileRel.getPicNum() : 0);
        } else {
            caseFileResultVO.setPicNum(1);
        }
    }


    @Override
    public Boolean delete(List<Long> ids) {
        appendixService.removeByBizId(ids, AppendixType.Complaint.COMPLAINT__PLAINTFF__FILE);
        return removeByIds(ids);
    }

    @Override
    public Boolean deleteByCaseIds(List<Long> caseIds) {
        LbQueryWrap<Plaintff> queryWrap = Wraps.<Plaintff>lbQ().in(Plaintff::getCaseId, caseIds);
        List<Plaintff> plaintffList = list(queryWrap);
        if (CollectionUtil.isNotEmpty(plaintffList)) {
            this.delete(plaintffList.stream().map(Plaintff::getId).collect(Collectors.toList()));
        }
        return true;
    }

    @Override
    public boolean updateSummarizeInfo(PlaintffSummarizeUpdateVO plaintffSummarizeUpdateVO) {
        Plaintff plaintff = new Plaintff();
        plaintff.setId(plaintffSummarizeUpdateVO.getId());
        plaintff.setSummarizeInfo(plaintffSummarizeUpdateVO.getSummarizeInfo());
        return this.superManager.updateById(plaintff);
    }
}


